package test.designmode.masterworker;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created by linshuo on 2018/3/3.
 */
public class Master {
    protected List<Thread> workThreads = new ArrayList<>();
    protected Queue<Object> jobQueue = new ConcurrentLinkedQueue<>();
    protected Queue<Object> resultQueue = new ConcurrentLinkedQueue<>();

    /**
     * 将jobQueue和results丢给worker代理; n条线程共用1个worker
     *
     * @param worker
     * @param threadNum
     */
    public Master(Worker worker, int threadNum) {
        worker.setResultQueue(resultQueue);
        worker.setJobQueue(jobQueue);
        for (int i = 0; i < threadNum; i++) {
            workThreads.add(new Thread(worker));
        }
    }

    /**
     * 是否所有任务都跑完了
     *
     * @return
     */
    public boolean isAllJobComplete() {
        for (Thread workThread : workThreads) {
            if (workThread.getState() != Thread.State.TERMINATED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 增加任务
     *
     * @param job
     */
    public void addJob(Object job) {
        jobQueue.add(job);
    }

    /**
     * 开启所有worker线程 (异步)
     */
    public void start() {
        for (Thread workThread : workThreads) {
            workThread.start();
        }
    }

    public Queue<Object> getResultQueue() {
        return resultQueue;
    }
}
